package com.mnt.washio.activities;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.mnt.washio.R;
import com.mnt.washio.objects.Address;
import com.mnt.washio.objects.Card;
import com.mnt.washio.objects.DateExtraObject;
import com.mnt.washio.objects.DateObject;
import com.mnt.washio.objects.TimeObject;
import com.mnt.washio.utils.SessionManager;
import com.mnt.washio.utils.Statics;
import com.mnt.washio.utils.network.WebServiceCommunicatorListener;
import com.mnt.washio.utils.network.ws.BaseWSControl;
import com.mnt.washio.utils.network.ws.BaseWSControl.WebServiceFlag;
import com.mnt.washio.utils.network.ws.GetCreditCardListWSControl;
import com.mnt.washio.utils.network.ws.GetDateOfOrderWSControl;
import com.mnt.washio.utils.network.ws.PlaceOrderWSControl;
import com.mnt.washio.views.CongraDialog;
import com.mnt.washio.views.CustomDialog;
import com.parse.ParseUser;

@SuppressLint("SimpleDateFormat")
public class OrderActivity extends BaseActivity implements OnClickListener,
		WebServiceCommunicatorListener {
	private TextView myTvLocation, myTvPickUpDate, myTvPickUpTime,
			myTvDropTime, myTvDropDate, myTvCard;
	private CustomDialog myDialogLocation, myDialogPickupDate,
			myDialogPickupTime, myDialogDropTime, myDialogDropDate,
			myDialogDropCard;
	private int myPositionLocation = 0, myPositionPickupDate = 0,
			myPositionPickupTime = 0, myPositionDropDate = 0,
			myPositionDropTime = 0, myPositionDropCard = 0;
	private Button myBtnPlaceOrder;
	private ProgressDialog pd;
	private String[] myArrayDatePickup;
	private ArrayList<String> myArrayListTimePickup;
	private ArrayList<DateExtraObject> myDateExtra;
	private ArrayList<DateObject> myDateDrop;
	private String[] myArrayDateDrop;
	private View myViewCreditCard;
	private EditText myEdtNote;
	private List<Card> myCards;
	private boolean readyCard = false;
	private ArrayList<Address> addresses;
	private HashMap<String, ArrayList<DateExtraObject>> zipCodes;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_order);
		initView();
		initProperties();
		addListener();

		getDateData(0);

		String stripeId = ParseUser.getCurrentUser().getString("stripeId");
		new GetCreditCardListWSControl(this, this, stripeId).execute();
	}

	@Override
	protected void initView() {
		super.initView();
		myTvLocation = (TextView) findViewById(R.id.tv_location);
		myTvPickUpTime = (TextView) findViewById(R.id.tv_pickup_time);
		myTvPickUpDate = (TextView) findViewById(R.id.tv_pickup_date);
		myTvDropDate = (TextView) findViewById(R.id.tv_drop_date);
		myTvDropTime = (TextView) findViewById(R.id.tv_drop_time);
		myBtnPlaceOrder = (Button) findViewById(R.id.btn_place_order);
		myTvCard = (TextView) findViewById(R.id.tv_no_card);
		myEdtNote = (EditText) findViewById(R.id.edt_note);
		myViewCreditCard = findViewById(R.id.ll_credit_card);
	}

	private void initProperties() {
		pd = new ProgressDialog(this);
		pd.setCancelable(false);
		zipCodes = SessionManager.getSessionManager(this).getZipCodes();
		addresses = SessionManager.getSessionManager(this).getOurArrayAddress();

		myTvLocation.setText(addresses.get(0).getAddress());
	}

	public void addListener() {
		myTvLocation.setOnClickListener(this);
		myTvPickUpTime.setOnClickListener(this);
		myTvPickUpDate.setOnClickListener(this);
		myTvDropTime.setOnClickListener(this);
		myTvDropDate.setOnClickListener(this);
		myBtnPlaceOrder.setOnClickListener(this);
		myViewCreditCard.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_location:
			showDialogLocation();
			break;
		case R.id.tv_pickup_date:
			if (null != myDialogPickupDate) {
				myDialogPickupDate.show();
			}
			break;
		case R.id.tv_pickup_time:
			if (null != myDialogPickupTime) {
				myDialogPickupTime.show();
			}
			break;
		case R.id.tv_drop_date:
			if (null != myDialogDropDate) {
				myDialogDropDate.show();
			}
			break;
		case R.id.tv_drop_time:
			if (null != myDialogDropTime) {
				myDialogDropTime.show();
			}
			break;
		case R.id.btn_place_order:

			if (!readyCard) {
				// do nothing
				Statics.showToast(this, "Getting cards");
			} else if (SessionManager.getSessionManager(this).getCardList()
					.size() == 0) {
				showAlerCard();
			} else {
				placeOrder();
			}

			break;
		case R.id.ll_credit_card:
			if (!readyCard) {
				// do nothing
				Statics.showToast(this, "Getting cards");
			} else if (SessionManager.getSessionManager(this).getCardList()
					.size() == 0) {
				showAlerCard();
			} else {
				showDialogCreditCard();
			}
			break;
		default:
			break;
		}
	}

	public void showDialogLocation() {
		final ArrayList<Object> arr = new ArrayList<Object>();
		for (Address address : addresses) {
			arr.add(address.getAddress());
		}

		myDialogLocation = new CustomDialog(this, arr, getResources()
				.getString(R.string.txt_adr), myPositionLocation);
		myDialogLocation.setOnClickItem(new CustomDialog.OnClickItem() {

			@Override
			public void Click(int position) {
				// TODO Auto-generated method stub
				position -= 1;
				myTvLocation.setText(arr.get(position).toString());
				myPositionLocation = position;

				getDateData(position);
			}
		});
		myDialogLocation.show();
	}

	public void parseDate() {
		myArrayDatePickup = new String[myDateExtra.size()];
		for (int i = 0; i < myDateExtra.size(); i++) {
			String date = myDateExtra.get(i).getDate();
			try {
				final String pattern = "yyyy-MM-dd'T'HH:mm:ss";
				final SimpleDateFormat sdf = new SimpleDateFormat(pattern);
				Date d = sdf.parse(date);
				myArrayDatePickup[i] = new SimpleDateFormat("EEE M/d")
						.format(d);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		showDialogPickupDate(myArrayDatePickup);
	}

	public void parseDateDrop(int positionDate, boolean isMornning) {
		myDateDrop = getDateDrop(positionDate, isMornning);
		parseDateDrop();
	}

	public void showDialogPickupDate(final String[] array) {
		List<Object> list = new ArrayList<Object>(Arrays.asList(array));
		myDialogPickupDate = new CustomDialog(this, list, getResources()
				.getString(R.string.pickup_date), myPositionPickupDate);
		myDialogPickupDate.setOnClickItem(new CustomDialog.OnClickItem() {

			@Override
			public void Click(int position) {
				// TODO Auto-generated method stub
				myTvPickUpDate.setText(array[position - 1]);
				myPositionPickupDate = position - 1;
				myPositionPickupTime = 0;
				parseTimePickUp(myPositionPickupDate);
				myDialogPickupTime.show();

			}
		});
		myTvPickUpDate.setText(array[0]);
		parseTimePickUp(0);
	}

	public void parseTimePickUp(int positionDate) {
		ArrayList<TimeObject> timeObj = myDateExtra.get(positionDate).getTime();
		String[] myArrayTimePickup = new String[timeObj.size() - 1];
		for (int i = 0; i < timeObj.size() - 1; i++) {
			myArrayTimePickup[i] = timeObj.get(i).getTime() + " - "
					+ timeObj.get(i + 1).getTime()
					+ (timeObj.get(i + 1).isMorning() ? "AM" : "PM");
		}
		myTvPickUpTime.setText(myArrayTimePickup[myPositionPickupTime]);
		showDialogPickupTime(myArrayTimePickup);
	}

	public void showDialogPickupTime(final String[] array) {
		List<Object> list = new ArrayList<Object>(Arrays.asList(array));
		myDialogPickupTime = new CustomDialog(this, list, getResources()
				.getString(R.string.pickup_time), myPositionPickupTime);
		myDialogPickupTime.setOnClickItem(new CustomDialog.OnClickItem() {

			@Override
			public void Click(int position) {
				// TODO Auto-generated method stub
				myTvPickUpTime.setText(array[position - 1]);
				myPositionPickupTime = position - 1;
				myPositionDropDate = 0;
				parseDateDrop(
						myPositionPickupDate,
						myDateExtra.get(myPositionPickupDate).getTime()
								.get(myPositionPickupTime).isMorning());
				myDialogDropDate.show();
			}
		});

		myPositionDropDate = 0;
		parseDateDrop(myPositionPickupDate,
				myDateExtra.get(myPositionPickupDate).getTime().get(0)
						.isMorning());
	}

	public void parseDateDrop() {
		myArrayDateDrop = new String[myDateDrop.size()];
		for (int i = 0; i < myDateDrop.size(); i++) {
			String date = myDateDrop.get(i).getDate();
			try {
				final String pattern = "yyyy-MM-dd'T'HH:mm:ss";
				final SimpleDateFormat sdf = new SimpleDateFormat(pattern);
				Date d = sdf.parse(date);
				myArrayDateDrop[i] = new SimpleDateFormat("EEE M/d")
						.format(d);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		showDialogDropDate(myArrayDateDrop);

	}

	public void showDialogDropDate(final String[] array) {
		List<Object> list = new ArrayList<Object>(Arrays.asList(array));
		myDialogDropDate = new CustomDialog(this, list, getResources()
				.getString(R.string.drop_date), myPositionDropDate);
		myDialogDropDate.setOnClickItem(new CustomDialog.OnClickItem() {

			@Override
			public void Click(int position) {
				// TODO Auto-generated method stub
				myTvDropDate.setText(array[position - 1]);
				myPositionDropDate = position - 1;
				myPositionDropTime = 0;
				parseTimeDrop(myPositionDropDate);
				myDialogDropTime.show();
			}
		});
		myTvDropDate.setText(array[0]);
		parseTimeDrop(0);
	}

	public void parseTimeDrop(int positionDateDrop) {
		ArrayList<TimeObject> timeObj = myDateDrop.get(positionDateDrop)
				.getTimeObject();
		String[] myArrayTimeDrop = new String[timeObj.size() - 1];
		for (int i = 0; i < timeObj.size() - 1; i++) {
			myArrayTimeDrop[i] = timeObj.get(i).getTime() + " - "
					+ timeObj.get(i + 1).getTime()
					+ (timeObj.get(i + 1).isMorning() ? "AM" : "PM");
		}
		myTvDropTime.setText(myArrayTimeDrop[myPositionDropTime]);
		showDialogDropTime(myArrayTimeDrop);
	}

	public void showDialogDropTime(final String[] array) {
		List<Object> list = new ArrayList<Object>(Arrays.asList(array));
		myDialogDropTime = new CustomDialog(this, list, getResources()
				.getString(R.string.drop_time), myPositionDropTime);
		myDialogDropTime.setOnClickItem(new CustomDialog.OnClickItem() {

			@Override
			public void Click(int position) {
				// TODO Auto-generated method stub
				myTvDropTime.setText(array[position - 1]);
				myPositionDropTime = position - 1;
			}
		});
	}

	public void showDialogCreditCard() {
		myCards = SessionManager.getSessionManager(this).getCardList();
		List<Object> list = new ArrayList<Object>(myCards);
		myDialogDropCard = new CustomDialog(this, list, "Credit Card",
				myPositionDropCard);
		myDialogDropCard.setOnClickItem(new CustomDialog.OnClickItem() {

			@Override
			public void Click(int position) {
				// TODO Auto-generated method stub
				position -= 1;
				myTvDropTime.setText(myCards.get(position).toString());
				myPositionDropCard = position;
			}
		});
		myDialogDropCard.show();
	}

	@Override
	public void onConnectionOpen(BaseWSControl wsControl, WebServiceFlag flag) {
		// TODO Auto-generated method stub
		pd.setMessage("Loading...");
		pd.show();
	}

	@Override
	public void onConnectionError(BaseWSControl wsControl, WebServiceFlag flag,
			String error) {
		// TODO Auto-generated method stub
		pd.dismiss();

		if (flag == WebServiceFlag.GET_DATE) {
			Statics.showToast(this, "Could not get time!");
			myBtnPlaceOrder.setEnabled(false);
			return;
		}

		if (flag == WebServiceFlag.GET_CREDIT_CARDS) {
			readyCard = true;
		}
		
		Statics.showToast(this, error);
	}

	@Override
	public void onConnectionDone(BaseWSControl wsControl, WebServiceFlag flag,
			Object result) {
		// TODO Auto-generated method stub
		pd.dismiss();

		if (flag == WebServiceFlag.GET_DATE && null != result) {
			myDateExtra = (ArrayList<DateExtraObject>) result;
			if (myDateExtra != null && myDateExtra.size() == 0) {
				Statics.showToast(this, "Could not get time!");
				myBtnPlaceOrder.setEnabled(false);
				return;
			}

			myBtnPlaceOrder.setEnabled(true);

			GetDateOfOrderWSControl getDate = (GetDateOfOrderWSControl) wsControl;
			zipCodes.put(getDate.zipCode, myDateExtra);

			parseDate();
		} else if (flag == WebServiceFlag.PLACE_ORDER) {
			if (null != result && result.toString().equals("Successful")) {
				new CongraDialog(this, CongraDialog.ORDER) {
					public void onDissmis() {
						Intent i = new Intent(OrderActivity.this,
								OrderStatusActivity.class);
						startActivity(i);
						finish();
					};
				}.show();
			}

		} else if (flag == WebServiceFlag.GET_CREDIT_CARDS && null != result) {
			myCards = (List<Card>) result;
			SessionManager.getSessionManager(this).setCardList(myCards);

			readyCard = true;

			if (myCards.size() > 0) {
				myPositionDropCard = 0;
				myTvCard.setText(myCards.get(0).toString());
			}
		}

	}

	@Override
	public void onUpdateData(BaseWSControl wsControl, WebServiceFlag flag,
			Object data) {
		// TODO Auto-generated method stub

	}

	public ArrayList<DateObject> getDateDrop(int positionDate,
			boolean isMornning) {
		DateExtraObject date = myDateExtra.get(positionDate);
		if (isMornning) {
			return date.getDropOffMorning();
		} else {
			return date.getDropOffAfternoon();
		}
	}

	public void showAlerCard() {
		new AlertDialog.Builder(this)
				.setTitle("Credit Card Required")
				.setMessage(
						"There is no Credit Card on file. Would you like to add one?")
				.setNegativeButton("No", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				})
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								Intent i = new Intent(OrderActivity.this,
										RegisterStep3Activity.class);
								startActivityForResult(i, 100);
							}
						}).show();

	}

	public void placeOrder() {
		if (null == myDateExtra || myDateExtra.size() == 0) {
			Statics.showToast(this, "Could not get time!");
			return;
		}

		String datePickUp = myDateExtra.get(myPositionPickupDate).getDate();
		String timePickUp = myDateExtra.get(myPositionPickupDate).getTime()
				.get(myPositionPickupTime).toString();

		String dateDroff = myDateDrop.get(myPositionDropDate).getDate();
		String timeDroff = myDateDrop.get(myPositionDropDate).getTimeObject()
				.get(myPositionDropTime).toString();

		try {
			datePickUp = datePickUp.replace(datePickUp.subSequence(11, 19),
					timePickUp.subSequence(0, 5) + ":00");
			dateDroff = dateDroff.replace(dateDroff.subSequence(11, 19),
					timeDroff.subSequence(0, 5) + ":00");
		} catch (Exception e) {
		}

		new PlaceOrderWSControl(this, this, addresses.get(0).getObjectId(),
				addresses.get(myPositionLocation).getZipCode(), myCards.get(
						myPositionDropCard).getId(), datePickUp, timePickUp,
				dateDroff, timeDroff, "", true, "", myEdtNote.getText()
						.toString()).execute();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		myCards = SessionManager.getSessionManager(this).getCardList();
		if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
			if (myCards.size() == 0) {
				myCards.add((Card) data.getSerializableExtra("card"));
				myPositionDropCard = 0;
				myTvCard.setText(myCards.get(0).toString());

				SessionManager.getSessionManager(this).setCardList(myCards);
			}
		}
	}

	private void getDateData(int pos) {
		if (zipCodes.containsKey(addresses.get(pos).getZipCode())) {
			myBtnPlaceOrder.setEnabled(true);
			myDateExtra = zipCodes.get(addresses.get(pos).getZipCode());
			parseDate();
		} else {
			new GetDateOfOrderWSControl(this, this, addresses.get(pos)
					.getZipCode()).execute();
		}
	}
}
